/**
 * PostgreSQL 数据库访问层
 * 
 * 纯 PostgreSQL 实现，不依赖 JSON 文件
 */

import { PrismaClient } from '@prisma/client'
import { buildToolUrl } from './utils/url'

// 类型定义
export interface StoredTool {
  id: string
  title: string
  description: string
  url: string
  image?: string | null // 工具截图
  deployPath?: string
  isDeployed: boolean
  originalFile?: string
  status: 'PENDING' | 'APPROVED' | 'REJECTED'
  categoryId: string
  userId: string
  createdAt: string
  updatedAt: string
  category?: {
    id: string
    name: string
    icon: string | null
  }
  user?: {
    id: string
    name: string
    email: string
  }
  _count?: {
    reviews: number
    favorites: number
  }
}

export interface StoredUser {
  id: string
  name: string
  email: string
  role: 'USER' | 'ADMIN'
  bio?: string
  avatar?: string
  website?: string
  password?: string  // 可选，用于兼容现有数据
  createdAt: string
  updatedAt: string
}

export interface StoredReview {
  id: string
  toolId: string
  userId: string
  rating: number
  comment?: string
  createdAt: string
  user?: {
    id: string
    name: string
    email: string
  }
}

export interface StoredFavorite {
  id: string
  toolId: string
  userId: string
  createdAt: string
}

// 用户会话接口
export interface UserSession {
  id: string
  userId: string
  token: string
  ip: string | null
  userAgent: string | null
  createdAt: string
  expiresAt: string
  isActive: boolean
}

// 全局 Prisma 客户端实例
declare global {
  var __prisma: PrismaClient | undefined
}

// 创建 Prisma 客户端，增加连接池配置
const prisma = globalThis.__prisma || new PrismaClient({
  datasources: {
    db: {
      url: process.env.DATABASE_URL,
    },
  },
  // 增加连接池配置
  log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error'],
})

if (process.env.NODE_ENV === 'development') {
  globalThis.__prisma = prisma
}

// 检查是否在构建时
function isBuildTime(): boolean {
  return process.env.NEXT_PHASE === 'phase-production-build'
}

// 数据库连接检查
async function ensureDatabaseConnection(): Promise<void> {
  // 构建时跳过数据库连接
  if (isBuildTime()) {
    console.log('⏭️ 构建时跳过数据库连接')
    return
  }

  try {
    await prisma.$connect()
    console.log('✅ PostgreSQL 数据库连接成功')
  } catch (error) {
    console.error('❌ PostgreSQL 数据库连接失败:', error)
    // 在出错时不抛出错误，而是让调用方处理
  }
}

// 工具相关操作
export async function getTools(request?: Request): Promise<StoredTool[]> {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空工具列表')
    return []
  }

  try {
    await ensureDatabaseConnection()

    const tools = await prisma.tool.findMany({
      include: {
        category: true,
        user: {
          select: { id: true, name: true, email: true }
        },
        _count: {
          select: {
            reviews: true,
            favorites: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    // 动态更新工具的URL，确保使用当前的基础URL
    return tools.map(tool => ({
      ...tool,
      deployPath: tool.deployPath || undefined,
      originalFile: tool.originalFile || undefined,
      createdAt: tool.createdAt.toISOString(),
      updatedAt: tool.updatedAt.toISOString(),
      url: tool.deployPath && request ? buildToolUrl(tool.deployPath, request) : tool.url
    }))
  } catch (error) {
    console.error('获取工具列表失败:', error)
    // 出错时返回空数组而不是抛出错误
    return []
  }
}

export async function getToolById(id: string): Promise<StoredTool | null> {
  try {
    await ensureDatabaseConnection()
    
    const tool = await prisma.tool.findUnique({
      where: { id },
      include: {
        category: true,
        user: {
          select: { id: true, name: true, email: true }
        },
        _count: {
          select: {
            reviews: true,
            favorites: true
          }
        }
      }
    })
    
    if (!tool) return null
    
    return {
      ...tool,
      deployPath: tool.deployPath || undefined,
      originalFile: tool.originalFile || undefined,
      createdAt: tool.createdAt.toISOString(),
      updatedAt: tool.updatedAt.toISOString()
    }
  } catch (error) {
    console.error('获取工具失败:', error)
    return null
  }
}

export async function addTool(toolData: Omit<StoredTool, 'id' | 'createdAt' | 'updatedAt'>): Promise<StoredTool> {
  await ensureDatabaseConnection()
  
  const tool = await prisma.tool.create({
    data: {
      title: toolData.title,
      description: toolData.description,
      url: toolData.url,
      image: toolData.image || null, // 添加 image 字段
      deployPath: toolData.deployPath,
      isDeployed: toolData.isDeployed,
      originalFile: toolData.originalFile,
      status: toolData.status,
      categoryId: toolData.categoryId,
      userId: toolData.userId
    },
    include: {
      category: true,
      user: {
        select: { id: true, name: true, email: true }
      }
    }
  })
  
  return {
    ...tool,
    deployPath: tool.deployPath || undefined,
    originalFile: tool.originalFile || undefined,
    createdAt: tool.createdAt.toISOString(),
    updatedAt: tool.updatedAt.toISOString()
  }
}

export async function updateTool(id: string, updateData: Partial<StoredTool>): Promise<StoredTool | null> {
  await ensureDatabaseConnection()
  
  const tool = await prisma.tool.update({
    where: { id },
    data: {
      ...(updateData.title && { title: updateData.title }),
      ...(updateData.description && { description: updateData.description }),
      ...(updateData.url && { url: updateData.url }),
      ...(updateData.deployPath !== undefined && { deployPath: updateData.deployPath }),
      ...(updateData.isDeployed !== undefined && { isDeployed: updateData.isDeployed }),
      ...(updateData.originalFile !== undefined && { originalFile: updateData.originalFile }),
      ...(updateData.status && { status: updateData.status }),
      ...(updateData.categoryId && { categoryId: updateData.categoryId }),
      updatedAt: new Date()
    },
    include: {
      category: true,
      user: {
        select: { id: true, name: true, email: true }
      }
    }
  })
  
  return {
    ...tool,
    deployPath: tool.deployPath || undefined,
    originalFile: tool.originalFile || undefined,
    createdAt: tool.createdAt.toISOString(),
    updatedAt: tool.updatedAt.toISOString()
  }
}

export async function deleteTool(id: string): Promise<boolean> {
  await ensureDatabaseConnection()
  
  try {
    await prisma.tool.delete({
      where: { id }
    })
    return true
  } catch (error) {
    console.error('删除工具失败:', error)
    return false
  }
}

// 用户相关操作
export async function getUsers(): Promise<StoredUser[]> {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空用户列表')
    return []
  }

  try {
    await ensureDatabaseConnection()

    const users = await prisma.user.findMany({
      orderBy: { createdAt: 'desc' }
    })

    return users.map(user => ({
      ...user,
      bio: user.bio || undefined,
      avatar: user.avatar || undefined,
      website: user.website || undefined,
      password: user.password || undefined,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString()
    }))
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 出错时返回空数组而不是抛出错误
    return []
  }
}

// 获取包含统计信息的用户列表 (管理员用)
export async function getUsersWithStats(): Promise<(StoredUser & {
  _count?: {
    tools: number
    reviews: number
    favorites: number
  }
})[]> {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空用户统计列表')
    return []
  }

  try {
    await ensureDatabaseConnection()

    const users = await prisma.user.findMany({
      include: {
        _count: {
          select: {
            tools: true,
            reviews: true,
            favorites: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    return users.map(user => ({
      ...user,
      bio: user.bio || undefined,
      avatar: user.avatar || undefined,
      website: user.website || undefined,
      password: user.password || undefined,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString(),
      _count: user._count
    }))
  } catch (error) {
    console.error('获取用户统计列表失败:', error)
    // 出错时返回空数组而不是抛出错误
    return []
  }
}

// 获取单个用户的详细信息（包含统计）
export async function getUserWithStats(userId: string): Promise<(StoredUser & {
  _count?: {
    tools: number
    reviews: number
    favorites: number
  }
}) | null> {
  // 构建时返回null
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空用户统计')
    return null
  }

  try {
    await ensureDatabaseConnection()

    const user = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      _count: {
        select: {
          tools: true,
          reviews: true,
          favorites: true
        }
      }
    }
  })

    if (!user) {
      return null
    }

    return {
      ...user,
      bio: user.bio || undefined,
      avatar: user.avatar || undefined,
      website: user.website || undefined,
      password: user.password || undefined,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString(),
      _count: user._count
    }
  } catch (error) {
    console.error('获取用户统计信息失败:', error)
    return null
  }
}

export async function getUserById(id: string): Promise<StoredUser | null> {
  await ensureDatabaseConnection()
  
  const user = await prisma.user.findUnique({
    where: { id }
  })
  
  if (!user) return null
  
  return {
    ...user,
    bio: user.bio || undefined,
    avatar: user.avatar || undefined,
    website: user.website || undefined,
    password: user.password || undefined,
    createdAt: user.createdAt.toISOString(),
    updatedAt: user.updatedAt.toISOString()
  }
}

export async function addUser(userData: Omit<StoredUser, 'id' | 'createdAt' | 'updatedAt'>): Promise<StoredUser> {
  await ensureDatabaseConnection()
  
  const user = await prisma.user.create({
    data: userData
  })
  
  return {
    ...user,
    bio: user.bio || undefined,
    avatar: user.avatar || undefined,
    website: user.website || undefined,
    password: user.password || undefined,
    createdAt: user.createdAt.toISOString(),
    updatedAt: user.updatedAt.toISOString()
  }
}

export async function updateUser(id: string, updateData: Partial<StoredUser>): Promise<StoredUser | null> {
  await ensureDatabaseConnection()
  
  const user = await prisma.user.update({
    where: { id },
    data: {
      ...updateData,
      updatedAt: new Date()
    }
  })
  
  return {
    ...user,
    bio: user.bio || undefined,
    avatar: user.avatar || undefined,
    website: user.website || undefined,
    password: user.password || undefined,
    createdAt: user.createdAt.toISOString(),
    updatedAt: user.updatedAt.toISOString()
  }
}

// 分类相关操作
export async function getCategories() {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空分类列表')
    return []
  }

  try {
    await ensureDatabaseConnection();

    return await prisma.category.findMany({
      orderBy: { name: 'asc' }
    })
  } catch (error) {
    // 处理权限错误，返回默认分类
    console.error('获取分类列表失败:', error);
    
    // 返回默认分类以避免前端报错
    return [
      { id: '1', name: '开发工具', icon: '💻', description: null, createdAt: new Date(), updatedAt: new Date() },
      { id: '2', name: '设计工具', icon: '🎨', description: null, createdAt: new Date(), updatedAt: new Date() },
      { id: '3', name: '效率工具', icon: '⚡', description: null, createdAt: new Date(), updatedAt: new Date() },
      { id: '4', name: '娱乐游戏', icon: '🎮', description: null, createdAt: new Date(), updatedAt: new Date() },
      { id: '5', name: '学习教育', icon: '📚', description: null, createdAt: new Date(), updatedAt: new Date() },
      { id: '6', name: '生活服务', icon: '🏠', description: null, createdAt: new Date(), updatedAt: new Date() }
    ];
  }
}

// 评论相关操作
export async function getReviews(): Promise<StoredReview[]> {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空评论列表')
    return []
  }

  try {
    await ensureDatabaseConnection()

    const reviews = await prisma.review.findMany({
      include: {
        user: {
          select: { id: true, name: true, email: true }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    return reviews.map(review => ({
      ...review,
      comment: review.comment || undefined,
      createdAt: review.createdAt.toISOString()
    }))
  } catch (error) {
    console.error('获取评论列表失败:', error)
    // 出错时返回空数组而不是抛出错误
    return []
  }
}

export async function getToolReviews(toolId: string): Promise<StoredReview[]> {
  try {
    await ensureDatabaseConnection()
    
    const reviews = await prisma.review.findMany({
      where: { toolId },
      include: {
        user: {
          select: { id: true, name: true, email: true }
        }
      },
      orderBy: { createdAt: 'desc' }
    })
    
    return reviews.map(review => ({
      ...review,
      comment: review.comment || undefined,
      createdAt: review.createdAt.toISOString()
    }))
  } catch (error) {
    console.error('获取工具评论失败:', error)
    return []
  }
}

export async function addReview(reviewData: Omit<StoredReview, 'id' | 'createdAt' | 'user'>): Promise<StoredReview> {
  await ensureDatabaseConnection()

  const review = await prisma.review.create({
    data: reviewData,
    include: {
      user: {
        select: { id: true, name: true, email: true }
      }
    }
  })

  return {
    ...review,
    comment: review.comment || undefined,
    createdAt: review.createdAt.toISOString()
  }
}

// 收藏相关操作
export async function getFavorites(): Promise<StoredFavorite[]> {
  // 构建时返回空数组
  if (isBuildTime()) {
    console.log('⏭️ 构建时返回空收藏列表')
    return []
  }

  try {
    await ensureDatabaseConnection()

    const favorites = await prisma.favorite.findMany({
      orderBy: { createdAt: 'desc' }
    })

    return favorites.map(favorite => ({
      ...favorite,
      createdAt: favorite.createdAt.toISOString()
    }))
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    // 出错时返回空数组而不是抛出错误
    return []
  }
}

export async function getUserFavorites(userId: string): Promise<StoredFavorite[]> {
  try {
    await ensureDatabaseConnection()
    
    const favorites = await prisma.favorite.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' }
    })
    
    return favorites.map(favorite => ({
      ...favorite,
      createdAt: favorite.createdAt.toISOString()
    }))
  } catch (error) {
    console.error('获取用户收藏失败:', error)
    return []
  }
}

export async function addFavorite(favoriteData: Omit<StoredFavorite, 'id' | 'createdAt'>): Promise<StoredFavorite> {
  await ensureDatabaseConnection()
  
  const favorite = await prisma.favorite.create({
    data: favoriteData
  })
  
  return {
    ...favorite,
    createdAt: favorite.createdAt.toISOString()
  }
}

export async function removeFavorite(userId: string, toolId: string): Promise<boolean> {
  await ensureDatabaseConnection()
  
  try {
    await prisma.favorite.deleteMany({
      where: {
        userId,
        toolId
      }
    })
    return true
  } catch (error) {
    console.error('移除收藏失败:', error)
    return false
  }
}

export async function isFavorited(userId: string, toolId: string): Promise<boolean> {
  await ensureDatabaseConnection()
  
  const favorite = await prisma.favorite.findFirst({
    where: {
      userId,
      toolId
    }
  })
  
  return !!favorite
}

/**
 * 创建新的用户会话
 */
export async function createUserSession(session: Omit<UserSession, 'id' | 'createdAt'>): Promise<UserSession> {
  const id = crypto.randomUUID()
  const now = new Date().toISOString()
  
  const result = await prisma.userSession.create({
    data: {
      id,
      userId: session.userId,
      token: session.token,
      ip: session.ip,
      userAgent: session.userAgent,
      expiresAt: new Date(session.expiresAt),
      isActive: session.isActive
    }
  })
  
  return {
    id: result.id,
    userId: result.userId,
    token: result.token,
    ip: result.ip,
    userAgent: result.userAgent,
    createdAt: result.createdAt.toISOString(),
    expiresAt: result.expiresAt.toISOString(),
    isActive: result.isActive
  }
}

/**
 * 获取用户的所有会话
 */
export async function getUserSessions(userId: string): Promise<UserSession[]> {
  const results = await prisma.userSession.findMany({
    where: {
      userId: userId
    },
    orderBy: {
      createdAt: 'desc'
    }
  })
  
  return results.map(session => ({
    id: session.id,
    userId: session.userId,
    token: session.token,
    ip: session.ip,
    userAgent: session.userAgent,
    createdAt: session.createdAt.toISOString(),
    expiresAt: session.expiresAt.toISOString(),
    isActive: session.isActive
  }))
}

/**
 * 终止用户会话
 */
export async function terminateUserSession(sessionId: string, userId: string): Promise<boolean> {
  try {
    const result = await prisma.userSession.updateMany({
      where: {
        id: sessionId,
        userId: userId
      },
      data: {
        isActive: false
      }
    })
    
    return result.count > 0
  } catch (error) {
    console.error('终止会话失败:', error)
    return false
  }
}

/**
 * 终止用户的所有会话（除了当前会话）
 */
export async function terminateAllUserSessions(userId: string, currentToken: string): Promise<number> {
  try {
    const result = await prisma.userSession.updateMany({
      where: {
        userId: userId,
        token: {
          not: currentToken
        }
      },
      data: {
        isActive: false
      }
    })
    
    return result.count
  } catch (error) {
    console.error('终止所有会话失败:', error)
    return 0
  }
}

/**
 * 验证会话是否有效
 */
export async function validateUserSession(token: string): Promise<UserSession | null> {
  try {
    const session = await prisma.userSession.findFirst({
      where: {
        token: token,
        isActive: true,
        expiresAt: {
          gt: new Date()
        }
      }
    })
    
    if (!session) {
      return null
    }
    
    return {
      id: session.id,
      userId: session.userId,
      token: session.token,
      ip: session.ip,
      userAgent: session.userAgent,
      createdAt: session.createdAt.toISOString(),
      expiresAt: session.expiresAt.toISOString(),
      isActive: session.isActive
    }
  } catch (error) {
    console.error('验证会话失败:', error)
    return null
  }
}
